<template>
  <div>
    <div id="components-form-demo-advanced-search" style="margin: 20px 10px">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          <span style="color: red">*</span>
          处理批次号：
          <a-select
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            :disabled="batchFalg"
            v-model="batchKey"
            style="width: 60%"
            @change="handleChange"
          >
            <a-select-option
              :tenantId="item.tenantId"
              :value="item.id"
              v-for="item in batchArray"
              :key="item.id"
              :batchNo="item.batchNo"
            >
              {{ item.batchNo }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <span style="color: red">*</span>
          运单号：<a-input :maxLength="128" v-model.trim="waybillNum" style="width: 60%" />
        </a-col>
        <a-col :span="6">
          <div>
            <a-button
              type="primary"
              style="
                background: #66b1ff;
                color: #fff;
                border: none;
                margin-left: 8px;
                margin-right: 20px;
              "
              @click="addTableRowBtach"
            >
              确认扫描
            </a-button>
            <a-button
              :disabled="tableList.length === 0"
              :loading="loading"
              type="primary"
              :style="
                tableList.length != 0
                  ? ' background: #66b1ff;color: #fff; border: none;margin-left: 8px;margin-right: 20px;'
                  : ''
              "
              @click="saveTableData"
            >
              提交数据
            </a-button>
          </div>
        </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table
        :data-source="tableList"
        :pagination="false"
        :scroll="{ x: 1300 }"
      >
        <!-- 客户编号 -->
        <a-table-column
          key="tenantId"
          data-index="tenantId"
          align="center"
          width="8%"
        >
          <span slot="title"> 客户编号</span>
          <template slot-scope="text, record">
            {{ record.tenantId }}
          </template>
        </a-table-column>
        <!-- 物流方式 -->
        <a-table-column
          key="logisticsId"
          data-index="logisticsId"
          align="center"
          width="18%"
        >
          <span slot="title">物流商</span>
          <template slot-scope="text, record">
            <span v-if="record.id || record.rowFlag">
              {{ record.logisticsName }}
            </span>
            <a-select
              placeholder="请选择物流商"
                 v-if="!record.id && !record.rowFlag"
              :style="
                record.logisticsId === null || record.logisticsId === ''
                  ? 'border: 1px solid #f00;border-radius:5px'
                  : 'border: 1px solid #ccc;border-radius:5px'
              "
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 100%"
               @change="
                (value, option) => handleChangeLogistics(value, option, record)
              "
            >
              <a-select-option
                v-for="item in record.logisticsList"
                :value="item.id"
                :key="item.id"
                :logisticsPlatform="item.logisticsPlatform"
                :serviceName="item.serviceName"
                :sysLogisticsId="item.sysLogisticsId"
                :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
              >
               <a-tooltip>
                  <template slot="title">
                    {{ item.serviceName }}/{{ item.logisticsPlatform }}
                  </template>
                  {{ item.serviceName }}/{{ item.logisticsPlatform }}
                </a-tooltip>
              </a-select-option>
            </a-select>
          </template>
        </a-table-column>
        <!-- 运单 -->
        <a-table-column
          key="waybillNm"
          data-index="waybillNm"
          align="center"
          width="15%"
        >
          <span slot="title">运单</span>
          <template slot-scope="text, record">
            {{ record.waybillNm }}
          </template>
        </a-table-column>
        <!-- 商品名称 -->
        <a-table-column
          key="skuName"
          data-index="skuName"
          align="center"
          width="15%"
        >
          <span slot="title">商品名称</span>
          <template slot-scope="text, record">
            {{ record.skuName }}
          </template>
        </a-table-column>
        <!-- 退件SKU -->
        <a-table-column key="sku" data-index="sku" align="center" width="15%">
          <span slot="title">退件SKU</span>
          <template slot-scope="text, record">
            <span v-if="record.id || record.rowFlag">
              {{ record.sku }}
            </span>
            <a-select
              v-if="!record.id && !record.rowFlag"
              style="width: 100%"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="(value, option) => changeSku(value, option, record)"
              placeholder="请选择SKU"
            >
              <a-select-option
                :value="v.id"
                v-for="v in record.RetreatStockArray"
                :key="v.id"
                :sku="v.sku"
                :name="v.skuName"
                :skuid="v.skuId"
                :productTag="v.productTag"
              >
                {{ v.sku }}
              </a-select-option>
            </a-select>
          </template>
        </a-table-column>
        <!-- 退件数量 -->
        <a-table-column
          key="productNumber"
          data-index="productNumber"
          align="center"
          width="15%"
        >
          <span slot="title">退件数量</span>
          <template slot-scope="text, record">
            <span v-if="record.id || record.rowFlag">
              {{ record.productNumber }}
            </span>
            <a-input-number
              v-if="!record.id && !record.rowFlag"
              :style="
                record.productNumber === null || record.productNumber === ''
                  ? 'border: 1px solid #f00;border-radius:5px'
                  : 'border: 1px solid #ccc;border-radius:5px'
              "
              size="small"
              v-model="record.productNumber"
              :min="1"
            />
          </template>
        </a-table-column>
        <!-- 箱数 -->
        <a-table-column
          key="packingNumber"
          data-index="packingNumber"
          align="center"
          width="8%"
        >
          <span slot="title"> 箱数</span>
          <template slot-scope="text, record">
            {{ record.packingNumber }}
          </template>
        </a-table-column>
        <!-- 长宽高 -->
        <a-table-column
          key="lengthNumber"
          data-index="lengthNumber"
          align="center"
          width="15%"
        >
          <span slot="title">长*宽*高(cm)</span>
          <template slot-scope="text, record" class="box-sizes">
            {{ record.lengthNumber }}* {{ record.wideNumber }}*
            {{ record.highNumber }}
          </template>
        </a-table-column>
        <!-- 重量 -->
        <a-table-column
          key="caratNumber"
          data-index="caratNumber"
          align="center"
          width="8%"
        >
          <span slot="title"> 重量(Kg)</span>
          <template slot-scope="text, record" class="box-sizes">
            <span> {{ record.caratNumber }} </span>
          </template>
        </a-table-column>
        <!-- //操作 -->
        <a-table-column
          key="operation"
          data-index="operation"
          title="操作"
          width="300px"
          align="center"
        >
          <template slot-scope="text, record">
            <a
              v-if="!record.id && !record.rowFlag"
              href="javascript:;"
              style="color: #2929e0; border-bottom: 1px solid #2929e0"
              @click="saveRow(record)"
              >保存</a
            >
            <a-divider v-if="!record.id && !record.rowFlag" type="vertical" />
            <a
              :disabled="record.file != '' && record.file != null"
              href="javascript:;"
              :style="
                record.file != '' && record.file != null
                  ? 'color: #ccc; border-bottom: 1px solid #ccc'
                  : 'color: #2929e0; border-bottom: 1px solid #2929e0'
              "
              @click="uplodImg(record)"
              >上传图片</a
            >
            <a-divider type="vertical" />
            <a
              href="javascript:;"
              style="color: #2929e0; border-bottom: 1px solid #2929e0"
              @click="lookImg(record)"
              >查看图片</a
            >
            <a-divider type="vertical" />
            <a-popconfirm
              title="确认要删除这行数据?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="delRowData(record)"
            >
              <a
                href="javascript:;"
                style="color: #f00; border-bottom: 1px solid #f00"
                >删除</a
              >
            </a-popconfirm>
          </template>
        </a-table-column>
      </a-table>
    </a-spin>

    <a-modal v-model="upLodVisible" title="上传图片">
      <template slot="footer">
        <a-button
          style="background: #d7d7d7; color: #fff; border: none"
          @click="
            () => {
              this.upLodVisible = false;
            }
          "
          >取消</a-button
        >
        <a-button :loading="loading" type="primary" @click="savaImg"
          >确定</a-button
        >
      </template>
      <p style="color: red">注：支持png、jpeg、jpg图片最多上传6张!</p>
      <a-upload
        :beforeUpload="beforeUploads"
        :action="baseUrl + `/by-file/uploadBatchFile`"
        list-type="picture-card"
        :file-list="fileList"
        @change="handleChangeImg"
        :headers="headers"
        @preview="handlePreview"
      >
        <div v-if="fileList.length < 6">
          <a-icon type="plus" />
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
    </a-modal>

    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible = false"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
    <!-- //查看图片 -->
    <a-modal v-model="lookImgVisible" title="查看图片" width="50%">
      <template slot="footer">
        <a-button
          style="background: #d7d7d7; color: #fff; border: none"
          @click="
            () => {
              this.lookImgVisible = false;
            }
          "
          >取消</a-button
        >
      </template>
      <span v-if="imgUrlArray.length >= 1">
        <img
          @click="lookImgs(item)"
          :src="item"
          :style="
            imgUrlArray.length <= 0
              ? ''
              : 'width: 200px; height: 200px; margin: 15px; cursor: pointer'
          "
          v-for="(item, i) in imgUrlArray"
          :key="i"
        />
      </span>
      <span v-else> 还未上传图片！ </span>
    </a-modal>
  </div>
</template>

<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import baseUrl from "@/utils/baseUrl";
import {
  by_retreat_BatchArray,
  by_retreat_RetreatStock,
  by_retreat_forecastInfo,
  by_retreat_forecastInfoGet,
  by_retreat_whSubmitBatch,
  by_retreat_delBatch,
} from "@/apis/clientSide/ReturnsList/ReturnsList";
import { warehouse, removefile,tenantService } from "@/apis/common";
import moment from "moment";
export default {
  created() {
    this.getBatchArray();
  },
  data() {
    return {
      lookImgVisible: false,
      imgUrlArray: [],
      baseUrl,
      fileList: [],
      previewImage: "",
      previewVisible: false,
      upLodVisible: false,
      tenantId: null,
      batchFalg: false,
      batchKey: null,
      batchArray: [],
      moment,
      spinning: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      waybillNum: null,
      loading: false,
      tableList: [],
      rowTabData: {
        batchNo: null,
        caratNumber: null,
        file: "",
        highNumber: null,
        lengthNumber: null,
        logisticsId: null,
        logisticsName: null,
        packingNumber: null,
        productNumber: null,
        productSumNumber: null,
        sku: null,
        skuId: null,
        skuName: null,
        tenantId: null,
        waybillNm: null,
        wideNumber: null,
      },
      headers: {
        authorization: "authorization-text",
        // ContentType: '["multipart/form-data"]',
        token: sessionStorage.getItem("tk"),
      },
      //每一行数据
      tabRowData: {},
      batchNo: null,
    };
  },
  methods: {
    //删除每一行
    async delRowData(record) {
      if (record.id) {
        let { code } = await by_retreat_delBatch(record.id);
        if (code === "10000") {
          let { code, responseBody } = await by_retreat_forecastInfoGet(
            this.batchNo
          );
          let { s } = await removefile(record.file.split(","));
          s;
          if (code === "200") {
            this.tableList = responseBody;
          }
        }
      } else {
        this.tableList.forEach(async (item, i) => {
          if (item.key === record.key) {
            this.tableList.splice(i, 1);
            this.$message.success("数据删除成功！");
            if (item.file != "") {
              let { code } = await removefile(item.file.split(","));
              code;
            }
          }
        });
      }
    },
    //保存每一行
    async saveRow(record) {
      if (
        record.logisticsId != null &&
        record.logisticsId != "" &&
        record.logisticsId != undefined &&
        record.productNumber != null &&
        record.productNumber != "" &&
        record.productNumber != undefined &&
        record.file != ""
      ) {
        let { code } = await by_retreat_forecastInfo(record.batchNo, record);
        if (code === "10000") {
          record.rowFlag = true;
          let { code, responseBody } = await by_retreat_forecastInfoGet(
            this.batchNo
          );
          if (code === "200") {
            this.tableList = responseBody;
          }
        }
      } else {
        this.$message.error("请检查必填项或是否上传图片！");
      }
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    beforeUploads(file) {
      return new Promise((resolve, reject) => {
        this.files = file;
        const isLt6M = file.size / 1024 / 1024 < 6;
        const img =
          file.type === "image/jpeg" ||
          file.type === "image/png" ||
          file.type === "image/jpg";
        if (!img) {
          this.$message.error("上传文件只能是 png、jpeg、jpg!");
          return reject(false);
        }
        if (!isLt6M) {
          this.$message.error("图片大小限制小于6MB!");
          return reject(false);
        }
        return resolve(true);
      });
    },
    lookImgs(url) {
      this.previewImage = url;
      this.previewVisible = true;
    },
    //上传传文件
    async handleChangeImg(file) {
      this.fileList = file.fileList;
      if (file.file.status === "done") {
        if (file.file.response) {
          this.$message.success("图片上传成功！");
          this.imgUrlArray.push(file.file.response.responseBody.join(","));
        } else {
          this.$message.error("图片上传失败！");
        }
      }
      if (file.file.status === "removed") {
        let { code } = await removefile(file.file.response.responseBody);
        if (code === "10000") {
          if (this.imgUrlArray.length >= 1) {
            this.imgUrlArray.forEach((item, i) => {
              if (item === file.file.response.responseBody.join(",")) {
                this.imgUrlArray.splice(i, 1);
              }
            });
          }
        }
      }
    },
    // 上传图片确定按钮
    savaImg() {
      if (this.imgUrlArray.length <= 0) {
        this.$message.error("请上传图片后保存！");
        return false;
      }
      this.tabRowData.file = this.imgUrlArray.join(",");
      this.tableList.forEach((item, i) => {
        if (item.key === this.tabRowData.key) {
          this.tableList[i] = this.tabRowData;
        }
      });
      this.upLodVisible = false;
    },
    //上传图片
    uplodImg(record) {
      this.tabRowData = record;
      this.upLodVisible = true;
      this.imgUrlArray = [];
      this.fileList = [];
    },
    changeSku(vaulue, option, record) {
      vaulue, (record.skuName = option.data.attrs.name);
      record.skuId = option.data.attrs.skuid;
      record.sku = option.data.attrs.sku;
      record.productTag = option.data.attrs.productTag;
    },
    //物流商改变
    handleChangeLogistics(value, option, record) {
      record.logisticsName = option.data.attrs.logisticsPlatform+'/'+ option.data.attrs.serviceName;
      record.logisticsId = option.data.attrs.sysLogisticsId+','+ option.data.attrs.sysLogisticsServiceItemId;
    },
    //改变批次
    handleChange(value, opton) {
      this.tenantId = opton.data.attrs.tenantId;
      this.batchNo = opton.data.attrs.batchNo;
    },
    //保存数据
    saveTableData() {
      this.loading = true;
      let passFlag = true;

      this.tableList.forEach((item) => {
        if (!item.id) {
          passFlag = false;
        }
      });
      if (passFlag) {
        setTimeout(async () => {
          let { code } = await by_retreat_whSubmitBatch(
            this.tableList[0].batchNo
          );
          if (code === "10000") {
            this.batchFalg = false;
            this.batchKey = "";
            this.loading = false;
            this.tableList = [];
            this.waybillNum = null;
          }
        }, 1000);
      } else {
        this.$message.error("请检查是否有未保存数据！");
        this.loading = false;
        return false;
      }
    },
    //扫描批次
    async addTableRowBtach() {
      if (
        this.batchKey != "" &&
        this.batchKey != null &&
        this.batchKey != undefined &&
        this.waybillNum != "" &&
        this.waybillNum != null
      ) {
        let obj = {
          batchNo: this.batchNo,
          caratNumber: null,
          file: "",
          highNumber: null,
          lengthNumber: null,
          logisticsId: null,
          logisticsName: null,
          packingNumber: null,
          productNumber: null,
          productSumNumber: null,
          sku: null,
          skuId: null,
          skuName: null,
          tenantId: this.tenantId,
          waybillNm: this.waybillNum,
          wideNumber: null,
          rowFlag: false,
        };
        if (
          this.tenantId != null &&
          this.tenantId != "" &&
          this.tenantId != ""
        ) {
          let res = await by_retreat_RetreatStock(this.tenantId);
          if (res.code === "200") {
            obj.RetreatStockArray = res.responseBody;
          }
          let logisticsList = await tenantService(this.tenantId);
          if (logisticsList.code === "200") {
                obj.logisticsList = logisticsList.responseBody;
          }

        }

        let { code, responseBody } = await by_retreat_forecastInfoGet(
          this.batchNo
        );
        if (code === "200") {
          this.tableList = responseBody;
          obj.key = Math.random();
          this.tableList.push(obj);
          this.batchFalg = true;
        }
      } else {
        this.$message.error("请选择批次或填写运单号！");
      }
    },
    //显示模态框
    lookImg(record) {
      this.imgUrlArray = record.file === "" ? [] : record.file.split(",");
      this.lookImgVisible = true;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //获取仓库
    async getwWrehouseList() {
      let { code, responseBody } = await warehouse({
        warehousePid: 0,
      });
      if (code === "200") {
        this.warehouse = [...responseBody];
      }
    },
    async getBatchArray() {
      let { code, responseBody } = await by_retreat_BatchArray();
      if (code === "200") {
        this.batchArray = responseBody;
      }
    },
    
  },
};
</script>

<style lang="less" scoped>
.pto-list {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  li {
    // width: 110px;
    // flex: 1;
    border: 1px solid #ccc;
    box-sizing: border-box;
    // padding: 3px 0;
    // height: 2rem;
  }
}
.pto-lists {
  display: flex;
  list-style: none;
  width: 100%;
  padding: 0;
  margin: 0;
  li {
    // width: 110px;
    flex: 1;
    border: 1px solid #ccc;
    box-sizing: border-box;
    // padding: 3px 0;
    // line-height: 2.7rem;
  }
}
/deep/.columns-tab {
  width: 10% !important;
  .columns {
    display: flex;
    div {
      // width: 110px;
      text-align: center;
      border: 1px solid #ccc;
    }
  }
}
/deep/.columns-tabs {
  width: 10% !important;
  .columns {
    display: flex;
    div {
      // width: 110px;
      text-align: center;
      border: 1px solid #ccc;
    }
  }
}
/deep/.ant-table-header-column {
  width: 100% !important;
}
</style>